﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using LibraryONTrack.dto;

namespace LibraryONTrack.Persistence.DataMappers
{
	public class PersonMapper : IDataMapper
	{
		protected  bool _isInitialized = false;
		private int _ordinal_id;
		private int _ordinal_name;

		private void InitializeMapper(IDataReader reader)
		{
			PopulateOrdinals(reader);
			_isInitialized = true;
		}

		public virtual void PopulateOrdinals(IDataReader reader)
		{
			_ordinal_id = reader.GetOrdinal("student_teacher_id");
			_ordinal_name = reader.GetOrdinal("name");			
		}

		public virtual object GetData(System.Data.IDataReader reader)
		{
			// This is where we define the mapping between the object properties and the 
			// data columns. The convention that should be used is that the object property 
			// names are exactly the same as the column names. However if there is some 
			// compelling reason for the names to be different the mapping can be defined here.

			// We assume the reader has data and is already on the row that contains the data 
			//we need. We don't need to call read. As a general rule, assume that every field must 
			//be null  checked. If a field is null then the nullvalue for that  field has already 
			//been set by the DTO constructor, we don't have to change it. 
			if (!_isInitialized)
			{
				InitializeMapper(reader);
			}

			Person dto = (Person) GetInstance();

			// Now we can load the data
			if (!reader.IsDBNull(_ordinal_id))
			{
				dto.Id = reader.GetInt64(_ordinal_id);
		}

			if (!reader.IsDBNull(_ordinal_name))
			{
				dto.Name = reader.GetString(_ordinal_name);
			}
			return dto;
		}

		public int GetRecordCount(System.Data.IDataReader reader)
		{
			Object count = reader["RecordCount"];
			return count == null ? 0 : Convert.ToInt32(count);
		}


		public virtual object GetInstance()
		{
			return new Person();
		}
	}
}
